//
//  WYNetHelper.m
//  test
//
//  Created by longtu on 15/4/22.
//  Copyright (c) 2015年 longtu. All rights reserved.
//

#import "WYDevHelper.h"

#import<SystemConfiguration/SCNetworkReachability.h>
#import <arpa/inet.h>

@interface WYHttpHelper () <NSURLConnectionDataDelegate>

@property(strong, nonatomic) NSMutableData *receiveData;
@property (strong, nonatomic) NSURLConnection* connection;
@end

@implementation WYHttpHelper

-(id) initWithDelegate:(id<WYHttpHelperDelegate>)delegate{
    if (self = [super init]) {
        self.delegate = delegate;
    }
    return self;
}

// 第一次打开时判断网络状态
+ (WYNetworkStatus ) connectedToNetwork{
    //创建零地址，0.0.0.0的地址表示查询本机的网络连接状态
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    //获得连接的标志
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    WYNetworkStatus status = WYNotReachable;
    //如果不能获取连接标志，则不能连接网络，直接返回
    if (didRetrieveFlags){
        //根据获得的连接标志进行判断
        BOOL isReachable = flags & kSCNetworkFlagsReachable;
        BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
        if((isReachable && !needsConnection)==YES){
            if ((flags& kSCNetworkReachabilityFlagsIsWWAN)==kSCNetworkReachabilityFlagsIsWWAN){
                status = WYReachableViaWWAN;
                if ((flags & kSCNetworkReachabilityFlagsTransientConnection) == kSCNetworkReachabilityFlagsTransientConnection){
                    status = WYReachableVia3G;
                } else if((flags & kSCNetworkReachabilityFlagsConnectionRequired) == kSCNetworkReachabilityFlagsConnectionRequired){
                    status = WYReachableVia2G;
                }
            }else{
                status = WYReachableViaWiFi;
            }
        }
    }
    return status;
}


// GET
-(void) sentRequest:(NSString *)temp_url_str{
    [self cancelRequest];
    if (![WYHttpHelper connectedToNetwork])
        return;
    
    NSURL *url = [NSURL URLWithString:temp_url_str];
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:18];
    self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
    NSLog(self.connection ? @"连接创建成功" : @"连接创建失败");
}
// GET Block
+ (void) getRequestWithURL:(NSString *)urlStr
        andNetRequestBlock:(WYHttpRequestBlock)block
                errorBlock:(WYHttpErrorBlock )errorBlock{
    WYHttpHelper *netRequest = [[WYHttpHelper alloc]init];
    netRequest.netRequestBlock = block;
    netRequest.httpErrorBlock = errorBlock;
    [netRequest cancelRequest];
    if (![self connectedToNetwork])
        return;
    
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *requset = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    netRequest.connection = [[NSURLConnection alloc]initWithRequest:requset delegate:netRequest];
    NSLog(netRequest.connection ? @"连接创建成功" : @"连接创建失败");
}
// POST 传入字典
- (void) sentPostRequest:(NSString *)urlstr
                  andDic:(NSDictionary *)dic{
    [self cancelRequest];
    if (![WYHttpHelper connectedToNetwork])
        return;
    
    NSURL *url = [NSURL URLWithString:urlstr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:28];
    //设置请求方式为POST，默认为GET
    [request setHTTPMethod:@"POST"];
    NSMutableString *bodyStr=[self getBody:dic];
    NSData *data=[bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
    NSLog(self.connection ? @"连接创建成功" : @"连接创建失败");
}
// POST 传入字典 Block
+ (void) postRequestWithURL:(NSString *)urlStr
                    andDic:(NSDictionary *)dic
        andNetRequestBlock:(WYHttpRequestBlock)block
                 errorBlock:(WYHttpErrorBlock )errorBlock{
    WYHttpHelper *netRequest = [[WYHttpHelper alloc]init];
    netRequest.netRequestBlock = block;
    netRequest.httpErrorBlock = errorBlock;
    [netRequest cancelRequest];
    // 判断网络
    if (![self connectedToNetwork])
        return;
    
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    [request setHTTPMethod:@"POST"];//设置请求方式为POST，默认为GET
    NSMutableString *bodyStr=[netRequest getBody:dic];
    NSData *data=[bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    netRequest.connection = [NSURLConnection connectionWithRequest:request delegate:netRequest];
    NSLog(netRequest.connection ? @"连接创建成功" : @"连接创建失败");
}
- (NSMutableString *) getBody:(NSDictionary *)dic{
    NSArray *arr=[dic allKeys];
    NSMutableString *body=[NSMutableString string];
    for(int i=0;i<[arr count]-1;i++){
        NSString *key=[arr objectAtIndex:i];
        NSString *value=[dic valueForKey:key];
        if (!value) {
            value=@"";
        }
        NSString *keyVlaue=[NSString stringWithFormat:@"%@=%@&",key,value];
        [body appendString:keyVlaue];
    }
    NSString *lastKey=[arr lastObject];
    NSString *lastValue=[dic valueForKey:lastKey];
    NSString *lastkeyVlaue=[NSString stringWithFormat:@"%@=%@",lastKey,lastValue];
    [body appendString:lastkeyVlaue];
    return body;
}

// POST 传入字符串
- (void) sentPostRequest:(NSString *)urlstr
                 andBody:(NSString *)body{
    [self cancelRequest];
    if (![WYHttpHelper connectedToNetwork])
        return;
    
    NSURL *url = [NSURL URLWithString:urlstr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:28];
    [request setHTTPMethod:@"POST"];//设置请求方式为POST，默认为GET
    NSData *data=[body dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
    NSLog(self.connection ? @"连接创建成功" : @"连接创建失败");
}
// POST 传入字符串 Block
+ (void) postRequestWithURL:(NSString *)urlStr
                   andBody:(NSString *)body
        andNetRequestBlock:(WYHttpRequestBlock)block
                 errorBlock:(WYHttpErrorBlock )errorBlock{
    WYHttpHelper *netRequest = [[WYHttpHelper alloc]init];
    netRequest.netRequestBlock = block;
    netRequest.httpErrorBlock = errorBlock;
    [netRequest cancelRequest];
    if (![self connectedToNetwork])
        return;
    
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    [request setHTTPMethod:@"POST"];//设置请求方式为POST，默认为GET
    NSData *data=[body dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    netRequest.connection = [NSURLConnection connectionWithRequest:request delegate:netRequest];
    NSLog(netRequest.connection ? @"连接创建成功" : @"连接创建失败");
}

- (void) cancelRequest {
    [self.connection cancel];
}

#pragma mark - URL Delegate
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    if (_netRequestBlock) {
        if (_httpErrorBlock) {
            self.httpErrorBlock(error);
        }
        return;
    }
    [self.delegate getdata:nil andIndifier:self.indifier requestSuccess:NO];
}

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    self.receiveData = [[NSMutableData alloc] init];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.receiveData appendData:data];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection{
    NSString *str = [[NSString alloc] initWithData:self.receiveData encoding:NSUTF8StringEncoding];
    NSError *error = nil;
    id someThing = [NSJSONSerialization JSONObjectWithData:self.receiveData options:NSJSONReadingAllowFragments error:&error];
    if (_netRequestBlock) {
        if ([someThing isKindOfClass:[NSDictionary class]] || [someThing isKindOfClass:[NSArray class]]){
            self.netRequestBlock(someThing);
        }else{
            self.netRequestBlock(str);
        }
        return;
    }
    if ([someThing isKindOfClass:[NSDictionary class]] || [someThing isKindOfClass:[NSArray class]]){
        [self.delegate getdata:someThing andIndifier:self.indifier requestSuccess:YES];
    }else{
        [self.delegate getdata:str andIndifier:self.indifier requestSuccess:YES];
    }
}

@end
